package com.example.jin.myplayer.myApplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jin.myplayer.R;
import com.example.jin.myplayer.http.LrcFileDownload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by JIN on 2017/11/2.
 */

public class LrcActivity extends AppCompatActivity implements GestureDetector.OnGestureListener{
    private TextView tv_lrc;
    private LinearLayout linearLayout;
    private int status;
    //广播接收器
    private StatusChangedReceiver receiver;

    private String lrc_data = null;
    private String filename = null;
    private String musicName = null;
    private String musicArtist = null;

    private AsyncDownload asyncDownload;
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lrc);

        tv_lrc = (TextView) findViewById(R.id.tv_lrc);
        linearLayout = (LinearLayout) findViewById(R.id.lrc_LinearLayout1);

        bindStatusChangedReceiver();
        tv_lrc.setText("当前没有播放歌曲");

        // 检查状态
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if (asyncDownload != null && !asyncDownload.isCancelled()) {
            asyncDownload.cancel(true);
        }
    }

    /**绑定广播接收器*/
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UDDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    /**发送控制广播*/
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        sendBroadcast(intent);
    }

    /**内部类，只处理播放状态*/
    class StatusChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    musicArtist = intent.getStringExtra("musicArtist");
                    musicName = intent.getStringExtra("musicName");
                    LrcActivity.this
                            .setTitle("歌词:" + musicName + " " + musicArtist);
                    try {
                        get_lrc(LrcActivity.this);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    /**下载或显示歌词*/
    private void get_lrc(Context context) throws IOException {
        //本程序内部储存空间的文件列表
        String[] files = context.fileList();
        if (musicName != null) {
            filename = musicName + ".lrc";
            List<String> fileList = Arrays.asList();
            if (fileList.contains(filename)) {
                //如果存在本地歌词，直接读出并显示，否则下载歌词
                Log.i("TAG", "has lrc file!");
                String string = drawLrcWord(filename);
                tv_lrc.setText(string);
            } else {
                // 判断网络状态
                ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cwjManager.getActiveNetworkInfo();
                // 网络可用则进行下载
                if (info != null && info.isAvailable()) {
                    Log.i("TAG", "has not lrc file!");
                    asyncDownload = new AsyncDownload();
                    asyncDownload.execute(LrcFileDownload.LRC_SEARCH_URL, musicName);
                } else {
                    Toast.makeText(getApplicationContext(), "当前网络不给力哦，请检测网络配置！", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**歌词正则表达*/
    private String drawLrcWord(String filename) {
        String lrc_word = "";
        Pattern pattern = Pattern.compile("\\[\\d{2}:\\d{2}.\\d{2}\\]");
        try {
            File file = new File(getApplicationContext().getFilesDir() + "/"
                    + filename);
            System.out.println(file.getPath());
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = "";

            while ((line = reader.readLine()) != null) {
                Matcher m = pattern.matcher(line);
                line = m.replaceAll("");
                line = line.replace("[ti:", "");
                line = line.replace("[ar:", "");
                line = line.replace("[al:", "");
                line = line.replace("[by:", "");
                line = line.replace("[i:", "");
                line = line.replace("]", "");
                line = line.contains("offset") ? "" : line;
                line = line.replace("url", "歌词来源");
                line = line.replace("null", "");
                lrc_word += line + "\n";

            }
            return lrc_word;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    /**解析下载*/
    class AsyncDownload extends AsyncTask{
        //执行时调用该方法
        @Override
        protected String doInBackground(Object[] params) {
            String url = null;
            try {
                url = LrcFileDownload.getSongLRCUrl(params[0].toString(), params[1].toString());
                lrc_data = LrcFileDownload.getHtmlCode(url);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());
            }
            return lrc_data;
        }

        //任务结束是调用该方法
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o == null) {
                tv_lrc.setText("当前没有歌词");
            } else {
                try {
                    // 写入文件
                    FileOutputStream outputStream = LrcActivity.this.openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write(o.toString().getBytes());
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String string = drawLrcWord(filename);
                tv_lrc.setText(string);
            }
        }

        //任务执行前调用该方法
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tv_lrc.setText("搜索歌词中...");
        }


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if(e1.getX() - e2.getX() > 150)//终点与起点的横坐标之差是否大于150像素
        {
            finish();
            overridePendingTransition(R.anim.to_right_enter, R.anim.to_right_exit);
            Toast.makeText(getApplicationContext(), "歌词", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(gestureDetector.onTouchEvent(ev)) //优先响应顶层VIEW的触屏事件
        {
            ev.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(ev);
    }
}
